package com.kehutong.crm.service.impl;

import com.kehutong.common.errcode.Result;
import com.kehutong.crm.dao.ForecastStatisticsDao;
import com.kehutong.crm.dto.DemandForecastStatisticsDto;
import com.kehutong.crm.entity.ForecastStatistics;
import com.kehutong.crm.service.DemandForecastService;
import com.kehutong.crm.service.ForecastStatisticsService;
import org.coraframework.inject.Inject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.connection.ThreadLocalCache;
import org.coraframework.orm.jdbc.execute.Condition;
import org.coraframework.orm.jdbc.execute.QueryCondition;
import org.coraframework.util.Objects;

import java.util.*;

/**
 * 预测统计服务接口实现类
 *
 * @author wupengfei
 */
public class ForecastStatisticsServiceImpl implements ForecastStatisticsService {

    private static final Logger logger = LoggerFactory.getLogger(ForecastStatisticsServiceImpl.class);

    @Inject
    private JdbcSession jdbcSession;

    @Inject
    private ForecastStatisticsDao forecastStatisticsDao;

    @Inject
    private DemandForecastService demandForecastService;

    @Override
    public Object rearrange(String id) {
        logger.info("重排序id=" + id);

        // 校验数据
        if (Objects.isBlank(id)) {
            logger.info("参数有误");
            return Result.badArgument();
        }

        // 查询数据
        List<String> idList = Arrays.asList(id.split("\\s*,\\s*"));
        List<ForecastStatistics> forecastStatisticsList = jdbcSession.findArray(ForecastStatistics.class).in("id", idList).and().eq("corpId", ThreadLocalCache.current().getCorpId()).exe();
        if (Objects.isEmpty(forecastStatisticsList) || idList.size() != forecastStatisticsList.size()) {
            logger.info("参数有误");
            return Result.badArgument();
        }
        forecastStatisticsList.sort(Comparator.comparingLong(ForecastStatistics::getSequence));

        // 设置排序值
        Map<String, Long> idSequenceMap = new HashMap<>();
        for (int i = 0; i < idList.size(); i++) {
            ForecastStatistics forecastStatistics = forecastStatisticsList.get(i);
            idSequenceMap.put(idList.get(i), forecastStatistics.getSequence());
        }

        // 更新db
        for (ForecastStatistics each : forecastStatisticsList) {
            each.setSequence(idSequenceMap.get(each.getId()));
        }
        jdbcSession.updateById(forecastStatisticsList);
        return Result.success();
    }

    @Override
    public void incrementNumber(String corpId, String type) {
        logger.info("增加数量corpId=" + corpId + "&type=" + type);
        QueryCondition query = Condition.createQuery();
        query.eq("corpId", corpId).and().eq("type", type);
        forecastStatisticsDao.incrementNumber(query);
    }

    @Override
    public void incrementTotalNumber(String corpId, String type) {
        logger.info("增加数量corpId=" + corpId + "&type=" + type);
        QueryCondition query = Condition.createQuery();
        query.eq("corpId", corpId).and().eq("type", type);
        forecastStatisticsDao.incrementTotalNumber(query);
    }

    @Override
    public List<ForecastStatistics> list() {
        logger.info("所有预测统计");
        String corpId = ThreadLocalCache.current().getCorpId();
        return jdbcSession.findArray(ForecastStatistics.class).eq("corpId", corpId).order("sequence").exe();
    }

    @Override
    public void statistics() {
        logger.info("统计");
        // 获取需求预测统计
        List<ForecastStatistics> dataList = new ArrayList<>();
        List<DemandForecastStatisticsDto> statisticsList = demandForecastService.getStatisticsByCorpIdAndType();
        for (int i = 0; i < statisticsList.size(); i++) {
            DemandForecastStatisticsDto each = statisticsList.get(i);
            ForecastStatistics item = Pool.newInstance(ForecastStatistics.class);
            item.setTotalNumber(each.getNumber());
            item.setSequence(i);
            item.setRequireNumber(each.getNumber());
            item.setCorpId(each.getCorpId());
            item.setTitle(each.getName());
            item.setType(each.getType());
            dataList.add(item);
        }
        insertOrUpdate(dataList);
    }

    private void insertOrUpdate(List<ForecastStatistics> dataList) {
        // 获取全部预测统计
        List<ForecastStatistics> forecastStatisticsList = jdbcSession.findArray(ForecastStatistics.class).exe();
        Map<String, ForecastStatistics> forecastStatisticsMap = new HashMap<>();
        for (ForecastStatistics each : forecastStatisticsList) {
            forecastStatisticsMap.put(each.getCorpId() + "-" + each.getType(), each);
        }

        // 获取增加和更新
        List<ForecastStatistics> insertList = new ArrayList<>();
        List<ForecastStatistics> updateList = new ArrayList<>();
        for (ForecastStatistics each : dataList) {
            ForecastStatistics forecastStatistics = forecastStatisticsMap.get(each.getCorpId() + "-" + each.getType());
            if (forecastStatistics != null) {
                each.setId(forecastStatistics.getId());
                each.setCreateUserId(forecastStatistics.getCreateUserId());
                each.setCreateTime(forecastStatistics.getCreateTime());
                updateList.add(each);
            } else {
                insertList.add(each);
            }
        }

        // 保存数据
        if (insertList.size() > 0) {
            jdbcSession.insert(insertList);
        }
        if (updateList.size() > 0) {
            jdbcSession.updateById(updateList);
        }
    }
}
